﻿using furion.blog.Application.Contracts;
using furion.blog.Domain.Shared;
using furion.blog.Domain.Shared.Vo.Image;
using furion.blog.Utils;
using Furion;
using Furion.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using SixLabors.ImageSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace furion.blog.Application
{
    public class ImageService : IImageService, ISingleton
    {
        private readonly IWebHostEnvironment _hostingEnvironment;

        public ImageService(IWebHostEnvironment hostEnvironment)
        {
            this._hostingEnvironment = hostEnvironment;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public async Task<List<ImageSaveVO>> Save(List<IFormFile> files)
        {
            return await SaveFile(files, false);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="files"></param>
        /// <param name="isCompress">是否压缩(120,480,720格式)</param>
        /// <returns></returns>
        private async Task<List<ImageSaveVO>> SaveFile(List<IFormFile> files, Boolean isCompress)
        {
            List<ImageSaveVO> ret = new List<ImageSaveVO>();
            await Task.Run(() =>
            {
                files.ForEach(t =>
                {
                    //相对路径
                    string ext = Path.GetExtension(t.FileName);
                    string fileName = IdUtil.Id() + ext;
                    string absPath = App.Configuration["AppInfo:SavePath"] + Constants.DS
                                     + string.Format("{0:yyyyMMdd}", DateTime.Now);
                    //绝对路径
                    string savePath = this._hostingEnvironment.WebRootPath + absPath;
                    if (!Directory.Exists(savePath))
                    {
                        Directory.CreateDirectory(savePath);
                    }

                    using var image = Image.Load(t.OpenReadStream());
                    if (ext == ".jpg" || ext == ".jpeg")
                    {
                        image.SaveAsJpegAsync(savePath + Constants.DS + fileName);
                    }
                    else if (ext == ".png")
                    {
                        image.SaveAsPngAsync(savePath + Constants.DS + fileName);
                    }
                    image.Dispose();

                    ret.Add(new ImageSaveVO
                    {
                        AbsPath = (absPath + Constants.DS + fileName).Replace("\\","/"),
                        Name = t.FileName,
                        Size = t.Length,
                        Uid = IdUtil.Id(),
                    });
                });
            });

            return ret;
        }

    }
}
